import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_bloc.dart';
import 'package:flutter_learn_vi/src/bean/bean_mine.dart';
import 'package:flutter_learn_vi/src/model/bloc_model.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'bloc_details_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/11.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class BlocSelectPage extends StatefulWidget {
  final bool isShowAppBar;

  BlocSelectPage({this.isShowAppBar = false});

  @override
  _BlocSelectPageState createState() => _BlocSelectPageState();
}

class _BlocSelectPageState extends State<BlocSelectPage>
    with
        AutomaticKeepAliveClientMixin,
        SingleTickerProviderStateMixin,
        BlocModel {
  //页面保持状态
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    getBlocDetails();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (widget.isShowAppBar) {
      return Scaffold(
        appBar: AppBar(
          title: Text("集团详情"),
          centerTitle: true,
        ),

        ///填充布局
        body: RefreshIndicator(
          onRefresh: () {
            getBlocDetails();
            ToastUtils.showToast("已刷新");
            return Future.value(true);
          },
          child: buildContainer(),
        ),
      );
    } else {
      return buildContainer();
    }
  }

  Widget buildContainer() {
    if (isLoading) {
      return LoadingWidget();
    }

    if (_blocBean == null) {
      return NoDataWidget(
        clickCallBack: () {
          getBlocDetails();
        },
      );
    }
    return Container(
      width: double.infinity,
      height: double.infinity,
      child: SingleChildScrollView(
        child: Column(
          children: [
            // buildHeaderRow(),
            buildCommonGridView(3),
            buildCommonGridView(1),
            buildCommonGridView(2),
          ],
        ),
      ),
    );
  }

  Widget buildHeaderRow() {
    return Container(
      margin: EdgeInsets.only(left: 8, right: 8, top: 8),
      padding: EdgeInsets.only(left: 8, top: 12),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(4))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: EdgeInsets.only(right: 12),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.blue),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: 8,
                ),
                Icon(
                  Icons.bookmark,
                  color: Colors.blue,
                ),
                SizedBox(
                  width: 8,
                ),
                Text(
                  "${_blocBean.blocName}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 16),
                ),
              ],
            ),
          ),
          buildCommonGridView(3, isMarging: false),
        ],
      ),
    );
  }

  Widget buildCommonGridView(int flag, {bool isMarging = true}) {
    String mineTitle = "";
    List<MineBean> mineList = [];
    if (flag == 1) {
      mineTitle = "煤矿企业";
      mineList = _blocBean.mineList;
    } else if (flag == 2) {
      mineTitle = "非煤矿企业";
      mineList = _blocBean.noMineList;
    } else {
      mineTitle = "集团";
      mineList = _blocBean.jiTuanList;
    }
    if (mineList == null || mineList.length == 0) {
      return NoDataWidget(
        clickCallBack: () {
          getBlocDetails();
        },
      );
    }
    return Container(
      margin: EdgeInsets.only(top: 22, bottom: 22),
      child: Container(
        color: Colors.white,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            mineTitle.length > 0
                ? Container(
              margin: EdgeInsets.only(
                  left: 10, right: 10, top: 12, bottom: 12),
              decoration:
              BoxDecoration(border: Border.all(color: Colors.blue)),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 4,
                    height: 22,
                    color: Colors.blue,
                  ),
                  SizedBox(
                    width: 4,
                  ),
                  Text(
                    mineTitle,
                    style: TextStyle(color: Colors.blue),
                  ),
                  SizedBox(
                    width: 8,
                  ),
                ],
              ),
            )
                : Container(),
            buildGridView(mineList, isMarging),
          ],
        ),
      ),
    );
  }

  Widget buildGridView(List<MineBean> mineList, bool isMarging) {
    return GridView.builder(
      physics: NeverScrollableScrollPhysics(),
      //缓存区域
      cacheExtent: 120,
      //内边距
      padding: EdgeInsets.all(8),
      shrinkWrap: true,
      //条目个数
      itemCount: mineList.length,
      //子Item排列规则
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        //子Item的最大宽度
        maxCrossAxisExtent: 150,
        //纵轴间距
        mainAxisSpacing: 2.0,
        //横轴间距
        crossAxisSpacing: 2.0,
        //子组件宽高长度比例
        childAspectRatio: 1.2,
      ),
      //懒加载构建子条目
      itemBuilder: (BuildContext context, int index) {
        MineBean mineBean = mineList[index];
        return buildListViewItemWidget(mineBean, isMarging);
      },
    );
  }

  BlocBean _blocBean;
  bool isLoading = true;

  Future<bool> getBlocDetails() async {
    //获取集团信息
    _blocBean = await getBlocDetailsRquest();
    isLoading = false;

    List<MineBean> list = _blocBean.mineEntityList;
    List<MineBean> list1 = [];
    List<MineBean> list2 = [];
    List<MineBean> list3 = [];
    if (list != null) {
      for (int i = 0; i < list.length; i++) {
        MineBean mineBean = list[i];
        String mineTag = mineBean.mineTag;

        /// jituan 集团 mine 煤炭企业  noMine 非煤企业
        if (mineTag == 'mine') {
          list1.add(mineBean);
        } else if (mineTag == 'noMine') {
          list2.add(mineBean);
        } else {
          list3.add(mineBean);
        }
      }
    }
    _blocBean.mineList = list1;
    _blocBean.noMineList = list2;
    _blocBean.jiTuanList = list3;
    if (!mounted) return true;
    setState(() {});
    return Future.value(true);
  }

  Widget buildListViewItemWidget(MineBean mineBean, bool isMarging) {
    return InkWell(
      onTap: () {
        NavigatorUtils.pushPage(context, BlocDetailsPage(mineBean: mineBean));
      },
      child: Container(
        padding: isMarging ? EdgeInsets.all(8) : EdgeInsets.zero,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(3))),
        child: Column(
          children: [
            buildImage(mineBean),
            SizedBox(
              height: 8,
            ),
            Text(
              "${mineBean.name}",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 12,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildImage(MineBean mineBean) {
    String url = mineBean.logoUrl;
    if (url == null || url.length == 0) {
      return ClipOval(
        child: Image.asset(
          "assets/images/3.0x/bg_header.png",
          width: 44,
          height: 44,
          fit: BoxFit.fill,
        ),
      );
    }
    return CachedNetworkImage(
      imageUrl: mineBean.logoUrl,
      width: 44,
      height: 44,
    );
  }
}
